package com.lkm.app_ui.netapi;

import android.os.SystemClock;

import com.lkm.app_ui.log.SystemLogger;
import com.lkm.frame.task.StopAble;
import com.lkm.java_okhttp.HttpClientHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.DateHelp;
import com.lkm.javatool.ServerTimeSync;
import com.lkm.javatool.URLHelp;
import com.lkm.javatool.lang.NameValueP;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;




public class HttpRequest {


//        System.out.println(getString(null, "https://dev.balance.api.satrace.cn/", new NameValueP[]{



    public static String getApiInfo(String url, NameValueP[] params) {
        String logParam = "";
        if (params != null) {
            for (NameValueP n : params) {
                if (n != null && n.getName() != null && n.getValue() != null)
                    logParam += "&" + n.getName() + "=" + n.getValue();
            }

        }
        String apiInfo = url + logParam;
        return apiInfo;
    }

    public static String sentContent(String url, String content, StopAble sa) {

        String resulrStr = null;
        try {

            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), content);

            Builder requestBuilder = new Builder().url(url);

            requestBuilder.post(body);

            Request request = requestBuilder.build();


            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }

            Response response = call.execute();

            try {
                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();

        }
        return resulrStr;
    }



    public static String getString(String url, NameValueP[] urlparams, String content,NameValueP[] head, StopAble sa) {
//        System.out.println("=======url " +getApiInfo(url, params));


        String resulrStr = null;
        try {
            RequestBody body = null;
            if (content!=null) {
                if (urlparams != null) {
                    url = URLHelp.appenParamsToUrl(url, urlparams);
                }
                body = RequestBody.create(MediaType.parse("application/json"), content == null ? "" : content);
            } else {
                FormEncodingBuilder feb = null;

                if (urlparams != null) {

                    feb = new FormEncodingBuilder();
                    for (NameValueP n : urlparams) {
                        if (n != null && n.getName() != null && n.getValue() != null)
                            feb.add(n.getName(), n.getValue());
                    }
                }
                try {
                    if (feb != null)
                        body = feb.build();
                } catch (Exception e) {
                    body = null;
                }
            }


            Builder requestBuilder = new Builder().url(url);
            Request request = null;
            if (body == null) {
                requestBuilder.get();
            } else {
                requestBuilder.post(body);
            }

            if(!CollectionHelp.isEmpty(head)){
                for (int i = 0; i < head.length; i++) {
                    NameValueP n = head[i];
                    if (n != null && n.getName() != null && n.getValue() != null)
                    requestBuilder.addHeader(head[i].getName(),head[i].getValue());
                }
            }


            request = requestBuilder.build();


            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }


            long requestTime = SystemClock.uptimeMillis();

            Response response = call.execute();

//			for (Certificate certificate : response.handshake().peerCertificates()) {
//				System.out.println(CertificatePinner.pin(certificate));

            try {
                String servertime = response.header("servertime");

                try {
                    long timeInMillis = DateHelp.parseStrToTimeInMillis(servertime);
                    long curTime = SystemClock.uptimeMillis();
                    ServerTimeSync.getInstance().setNetLoadServerTime(curTime - requestTime, System.currentTimeMillis(), timeInMillis);

                    SystemLogger.Net.onServerTime(timeInMillis);
                } catch (Exception e) {

                }

                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();

        }
        return resulrStr;
    }

    static {

        com.lkm.market2_0.netapi.HttpRequest.VOID();
    }
    public static OkHttpClient getHttpClient(){
        return  com.lkm.market2_0.netapi.HttpRequest.getHttpClient();
    }



//        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);





////            setCertificates(Config.instance.getHttpsCertificates());





////                        .add("dev.balance.api.satrace.cn", "sha1
//////                        .add("dev.balance.api.satrace.cn", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
//////                        .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
//////                        .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")





//        ((CookieManager) getHttpClient().getCookieHandler()).getCookieStore().removeAll();











//    public static void setCertificates(InputStream... certificates) {

//            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());




//                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));











//                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());








//            getHttpClient().setSslSocketFactory(sslContext.getSocketFactory());








}
